import { ref, reactive, shallowRef } from 'vue';
import echarts from '@/echarts';
import { EChartsOption } from 'echarts';
import { EChartsType } from 'echarts/core';
import type { LineBarChartType, MuSelectValueType } from '../data';

import { getHtmlFontPX, handleChartResize } from '@/utils/base';
import { useAutoTooltip } from '@/utils/echartsAutoTooltip';
import ThemeColor from '@/themeColor';
import { colorList } from '../config';

export default function (props?: {
  showHandler?: (visible: boolean, type: number, selectValue: MuSelectValueType) => void;
  type: number;
}): LineBarChartType {
  const chartRef = shallowRef<EChartsType>();
  const container = ref<HTMLDivElement | undefined>();
  const chart = reactive<LineBarChartType['chart']>({
    selectValue: [4, 8, 9],
    initChart,
    resizeChart
  });
  const xAxisPreData = ref<any[]>();

  /**
   * @returns 返回option配置
   */
  function getOption() {
    const option: EChartsOption = {
      color: colorList,
      textStyle: {
        color: ThemeColor.chartFontColor
      },

      tooltip: {
        confine: true,
        axisPointer: {
          lineStyle: {
            width: 2,
            color: '#ffeb7b'
          }
        },
        className: 'tooltip-review',
        formatter: (params: any) => {
          let resStr: string = `<div>${params[0].axisValueLabel}</div>`;
          params.forEach((item: any) => {
            resStr += `
            <div class="tooltip-item">
              <div class="tooltip-label-icon">
                <span class="tooltip-icon" style="background-color: 
                ${item.color.colorStops ? '#4992ff' : item.color}"></span>
                <span class="tooltip-label">${item.seriesName}：</span>
              </div>
              <span class="tooltip-value">${item.value}</span>
            </div>
            `;
          });
          return resStr;
        },
        // 通过坐标轴来触发
        trigger: 'axis',
        textStyle: {
          fontSize: getHtmlFontPX(0.75)
        }
      },
      // containLabel 为 true 的时候：
      // grid.left grid.right grid.top grid.bottom grid.width grid.height 决定的是包括了坐标轴标签在内的所有内容所形成的矩形的位置。
      // 这常用于『防止标签溢出』的场景，标签溢出指的是，标签长度动态变化时，可能会溢出容器或者覆盖其他组件。
      grid: {
        top: '20%',
        left: '5%',
        right: '10%',
        bottom: '5%',
        containLabel: true
      },
      toolbox: {
        show: false,
        right: !props?.showHandler ? '2%' : '3%',
        iconStyle: {
          borderColor: ThemeColor.chartFontColor
        },
        emphasis: {
          iconStyle: {
            borderColor: '#ffeb7b'
          }
        },
        itemGap: Number(getHtmlFontPX(0.25).replace('px', '')),
        itemSize: Number(getHtmlFontPX(0.875).replace('px', '')),
        feature: {
          magicType: {
            type: ['line', 'bar'],
            title: {
              line: '切换为折线图', // 将"Switch to Line Chart"改为中文
              bar: '切换为柱状图' // 将"Switch to Bar Chart"改为中文
            }
          }
        }
      },
      xAxis: {
        type: 'value',
        axisTick: {
          show: false
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#DCE2E8'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: ThemeColor.chartLineColor
          }
        }
      },
      yAxis: {
        type: 'category',
        axisLabel: {
          fontSize: getHtmlFontPX(0.75)
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: ThemeColor.chartLineColor
          }
        },
        axisTick: {
          show: false
        },
        data: xAxisPreData.value
      },
      series: []
    };
    return option;
  }

  /**
   * 初始化图表
   * @param container 图表容器id
   */
  function initChart(chartData?: any[]): any {
    if (!container.value) return;
    const option: EChartsOption = getOption();
    const seriesArr: any[] = [];

    if (chartData?.length) {
      chartData.forEach((item: any) => {
        seriesArr.push({
          name: item.name,
          type: item.type,
          barWidth: 15,
          data: item.data,
          label: {
            show: true,
            position: 'right',
            color: '#fff',
            fontSize: 12
          },
          smooth: true,
          lineStyle: {
            width: 3
          },
          itemStyle: item?.itemStyle || {
            borderRadius: [5, 5, 5, 5],
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              {
                offset: 0,
                color: '#2352CC'
              },
              {
                offset: 0.5,
                color: '#3CB6FF'
              },
              {
                offset: 1,
                color: '#94D4FF'
              }
            ])
          }
        });
        const xAxisData: any[] = [];
        item.data.forEach((row: any) => {
          xAxisData.push(row.name);
        });
        xAxisPreData.value = xAxisData;
      });
    }

    option.series = seriesArr;
    option.yAxis.data = xAxisPreData.value;
    chartRef.value = echarts.init(container.value);
    chartRef.value && chartRef.value.setOption(option);

    // 添加自动轮播功能
    if (chartRef.value && seriesArr.length > 0) {
      const { start, stop } = useAutoTooltip(chartRef.value as unknown as any, {
        interval: 2500,
        seriesIndex: 0
      });

      // 延迟启动，确保图表渲染完成
      setTimeout(() => {
        start();
      }, 1000);

      // 存储停止函数，供组件卸载时调用
      chart.stopTooltip = stop;
      return stop;
    }
  }

  /**
   * @description 重新set一下resize后的字体 不然会有偏移
   */
  function resetFontSize() {
    const option = getOption();
    option.yAxis.data = xAxisPreData.value;
    // 需要重新计算字体不然依旧会有点偏差
    chartRef.value && chartRef.value.setOption(option);
  }

  /**
   * @description 处理图表resize
   */
  function resizeChart() {
    if (chartRef.value) {
      handleChartResize(chartRef.value);
      resetFontSize();
    }
  }

  return {
    chart,
    container,
    chartRef,
    getOption
  };
}
